﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
using ZX.WebApp.CrmWorkFlowService;
using ZX.WebApp;
namespace ZX.WebApp.Crm.BasePages
{
	public partial class WfMonitorPic : System.Web.UI.Page
	{
        WorkFlowServiceClient client = new WorkFlowServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            string workflowId = "";
            string workflowInsId = "";
            Bitmap objBitmap;
            try
            {
                if (!this.IsPostBack)
                {
                    if (Request["workflowId"] != null && Request["WorkFlowInstanceId"] != null)
                    {
                        string[] str = client.GetMaxWorkTaskPosition(Request["workflowId"].ToString()).Split(',');
                        if (str.Length == 2)
                        {
                            objBitmap = new Bitmap(Convert.ToInt32(str[0]) + 150, Convert.ToInt32(str[1]) + 50);
                        }
                        else
                        {
                            objBitmap = new Bitmap(1000, 1000);
                        }
                        Graphics objGraphics = Graphics.FromImage(objBitmap);
                        workflowId = Request["workflowId"].ToString();
                        workflowInsId = Request["WorkFlowInstanceId"].ToString();
                        InitTaskMapData(workflowId, workflowInsId, objGraphics);
                        InitLinkMapData(workflowId, workflowInsId, objGraphics);
                        objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void drawTaskBitmap(Graphics gc, string taskCaption, string operType, int x, int y, bool isPass, bool isCurrent, string taskDes, string taskStatus,string operContentText)
        {
            Rectangle bounds;
            Bitmap taskBitmap = null;
            Font font;
            StringFormat alignVertically;
            Point pt = new Point(0, 0);
            Brush bcolor;
            int Captionx;
            string noPassflag = "灰";//表示灰色图片
            pt.X = x;
            pt.Y = y;
            font = new Font("Arial", 8);
            alignVertically = new StringFormat();
            alignVertically.LineAlignment = StringAlignment.Center;//指定文本在布局矩形中居中对齐
            if (isPass) noPassflag = ""; else noPassflag = "灰";
            switch (operType)
            {
                case "1"://启动节点
                    taskBitmap = new Bitmap(Server.MapPath("../images/HF_Start.png"));
                    break;
                case "2"://终止节点 
                    taskBitmap = new Bitmap(Server.MapPath("../images/HF_Stop.png"));
                    break;
                case "3"://交互节点 
                    if (taskStatus == "1" || taskStatus == "2" || taskStatus == "5")
                     {
                         if (operContentText != "" && taskDes !="")
                         {
                             taskBitmap = new Bitmap(Server.MapPath("../images/HF_AlterState.gif"));
                         }
                         else
                         {
                             taskBitmap = new Bitmap(Server.MapPath("../images/HF_Alter.gif"));
                         }
                     }
                     else if (taskStatus == "3")
                     {
                         taskBitmap = new Bitmap(Server.MapPath("../images/HF_AlterEnd.gif"));
                     }
                     else
                     {
                         taskBitmap = new Bitmap(Server.MapPath("../images/HF_Alter.gif"));
                     }
                     break;
                case "4"://控制节点 
                     taskBitmap = new Bitmap(Server.MapPath("../images/HF_Ctrl.png"));
                    break;
                case "5"://查看节点 
                    taskBitmap = new Bitmap(Server.MapPath("../images/查看节点" + noPassflag + ".JPG"));
                    break;
                case "6"://子流程节点 
                    taskBitmap = new Bitmap(Server.MapPath("../images/子流程节点" + noPassflag + ".JPG"));
                    break;
                default:
                    taskBitmap = new Bitmap(Server.MapPath("../images/查看节点" + noPassflag + ".JPG"));
                    break;
            }
            if (isCurrent)
            {
                bcolor = Brushes.Red;
            }
            else bcolor = Brushes.Black;//当前节点
            bounds = new Rectangle(pt, taskBitmap.Size);
            gc.DrawImage(taskBitmap, bounds.Left, bounds.Top -70);

            //SizeF sizeF = gc.MeasureString(taskCaption, font);
            Captionx = bounds.Left - 30 + bounds.Width / 2;

            if (taskDes != "")
            {
                if (operType == "1" || operType == "2")
                {
                    //当前审核人
                    gc.DrawString(taskDes, font, bcolor, Captionx, bounds.Top - 32, alignVertically);
                    bcolor = Brushes.Black;
                    //当前节点
                    gc.DrawString(taskCaption, font, bcolor, Captionx, bounds.Top - 73, alignVertically);
                }
                else
                {
                    // //当前审核人
                    gc.DrawString(taskDes, font, bcolor, Captionx, bounds.Top - 32, alignVertically);
                    bcolor = Brushes.White;
                    //当前节点
                    gc.DrawString(taskCaption, font, bcolor, Captionx, bounds.Top - 60, alignVertically);
                }
            }
            else
            {
                //当前审核人
                gc.DrawString(taskDes, font, bcolor, Captionx, bounds.Top - 32, alignVertically);
                bcolor = Brushes.Black;//当前节点
                gc.DrawString(taskCaption, font, bcolor, Captionx, bounds.Top - 32, alignVertically);
              
            }
        }
        private void drawLinkBitMap(Graphics gs, string linkBreakX, string linkBreakY,
                                    int starttaskX, int starttaskY, int endtaskX, int endtaskY,int startLX,int startLY,int endLX,int endLY,Color clr, string linkDes)
        {
            ArrayList breakPointX = new ArrayList();
            ArrayList breakPointY = new ArrayList();

	        // 连接线起点
		    Point startPoint = new Point(starttaskX-startLX,starttaskY-startLY);			
		
		    // 连接线终点
            Point endPoint = new Point(endtaskX - endLX, endtaskY - endLY);	

            string[] BreakX;
            string[] BreakY;
            breakPointX.Add(startPoint.X);
            breakPointY.Add(startPoint.Y-70);

            if (linkBreakX.ToString() != "")
            {
                if (linkBreakX.IndexOf(",") != -1)
                {
                    BreakX = linkBreakX.Split(",".ToCharArray());
                    BreakY = linkBreakY.Split(",".ToCharArray());
                    for (int i = 0; i < BreakX.Length; i++)
                    {
                        breakPointX.Add(BreakX[i]);
                        breakPointY.Add(Convert.ToInt32(BreakY[i])-70);
                    }
                }
                else
                {
                    breakPointX.Add(linkBreakX);
                    breakPointY.Add(Convert.ToInt32(linkBreakY)-70);
                }
            }
            breakPointX.Add(endPoint.X);
            breakPointY.Add(endPoint.Y-70);
         
            Pen pen = new Pen(clr, 2);

            for (int i = 0; i < breakPointX.Count - 2; i++)
            {
                Point bp = new Point(Convert.ToInt16(breakPointX[i]), Convert.ToInt16(breakPointY[i]));
                Point bp2 = new Point(Convert.ToInt16(breakPointX[i + 1]), Convert.ToInt16(breakPointY[i + 1]));
                gs.DrawLine(pen, bp, bp2);
            }
            //画最后一条带箭头的  
            if (breakPointX.Count >= 2)
            {

                int ittX = Convert.ToInt16(breakPointX[breakPointX.Count - 2]);
                int ittY = Convert.ToInt16(breakPointY[breakPointX.Count - 2]);
                int itt2X = Convert.ToInt16(breakPointX[breakPointX.Count - 1]);
                int itt2Y = Convert.ToInt16(breakPointY[breakPointX.Count - 1]);
                Point tt = new Point(ittX, ittY);
                Point tt2 = new Point(itt2X, itt2Y);
                AdjustableArrowCap Arrow = new AdjustableArrowCap(5,5);
                pen.CustomEndCap = Arrow;
                gs.DrawLine(pen, tt, tt2);
                //			}

                //画注释	
                if (linkDes == "")
                    return;
                Font font = new Font("Arial", 8);
                StringFormat alignVertically = new StringFormat();
                alignVertically.LineAlignment = StringAlignment.Center;//指定文本在布局矩形中居中对齐
                SizeF sizeF = gs.MeasureString(linkDes, font);
                int x = (Convert.ToInt16(breakPointX[0]) + Convert.ToInt16(breakPointX[1]) - (int)sizeF.Width) / 2;
                int y = (Convert.ToInt16(breakPointY[0]) + Convert.ToInt16(breakPointY[1])) / 2;
                gs.DrawString(linkDes, font, Brushes.Blue, x, y, alignVertically);
            }

        }
        private void InitTaskMapData(string workflowId, string workflowInsId, Graphics gc)
        {
            
            DataTable tasktable = client.GetWorkTasks(workflowId);
            string taskCaption = "";
            int taskX;
            int taskY;
            string operType = "";
            string taskId = "";
            string taskStatus = "0";
            string operContentText = "";
            string taskDes = "";
            bool isPass;//是否通过
            bool isCurrent = false;//是否是当前节点

            gc.Clear(System.Drawing.Color.FromArgb(255, 253, 244));   // 改变背景颜色
            foreach (DataRow dr in tasktable.Rows)
            {
                taskId = dr["WorkTaskId"].ToString();
                taskCaption = dr["TaskCaption"].ToString();
                taskX = Convert.ToInt16(dr["iXPosition"]);
                taskY = Convert.ToInt16(dr["iYPosition"]);
                operType = dr["TaskTypeId"].ToString();
                DataTable tables = client.GetTaskInstance(workflowInsId,taskId);
                if (tables == null)
                {
                    taskStatus = "0";
                }
                else if (tables.Rows.Count > 0)
                {
                    string statues = string.Empty;
                    foreach (DataRow item in tables.Rows)
                    {
                        if (item["Status"].ToString() == "1" || item["Status"].ToString() == "2" || item["Status"].ToString() == "5")
                        {
                            statues = item["Status"].ToString();
                            break;
                        }
                    }
                    taskStatus = statues != "" ? statues : "3";
                }
                else
                {
                    taskStatus = "0";
                }
                isPass = client.IsPassJudge(workflowId, workflowInsId, taskId, WorkFlowConst.Command_And);
                //if (taskStatus == WorkFlowConst.TaskStatus_2) isCurrent = true; else isCurrent = false;
                isCurrent = client.IsCurrentTask(workflowInsId, taskId);
                if (tables == null)
                {
                    taskDes = "";
                }
                else if (taskStatus == "1" || taskStatus == "2" || taskStatus == "5") //任务节点未完成
                {
                    taskDes = client.GetTaskOperDoneWhoMsg(taskId,workflowInsId);
                    if (tables.Select("OperContentText <> ''").Length > 0)
                    {
                        operContentText = (tables.Select("OperContentText <> ''")[0])["OperContentText"].ToString();
                    }
                }
                else //任务节点已完成
                {
                    taskDes = client.GetTaskDoneWhoMsg(taskId, workflowInsId);
                }
                drawTaskBitmap(gc, taskCaption, operType, taskX, taskY, isPass, isCurrent, taskDes, taskStatus, operContentText);

            }


        }
        private bool isFromStartTask(string workflowId, string workflowInsId, string startTaskId, string endTaskId)
        {

            DataTable dt1 = client.GetTaskInstance(workflowInsId, endTaskId);
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                string ptaskInsId = dt1.Rows[0]["PreviousTaskInstanceId"].ToString();//根据后端节点模板找到前一任务实例
                DataTable dt2 = client.GetWorkTaskInstanceTable(ptaskInsId);//根据前一任务实例找到任务模板
                if (dt2 != null && dt2.Rows.Count > 0)
                {
                    string staskid = dt2.Rows[0]["WorktaskId"].ToString();
                    if (staskid == startTaskId)
                        return true;
                }
                return false;
            }
            return false;
        }
        private void InitLinkMapData(string workflowId, string workflowInsId, Graphics gc)
        {
            DataTable linktable = client.GetWorkTaskLineView(workflowId);
            string linkDes = "";
            string startTaskId = "";
            string endTaskId = "";
            string linkBreakX;
            string linkBreakY;
            int starttaskX;
            int starttaskY;
            int endtaskX;
            int endtaskY;

            int startLX;
            int startLY;
            int endLX;
            int endLY;


            bool started;
            bool ended;
            bool fromStart;
            bool isPass;//是否通过
            Color linkColor;

            foreach (DataRow dr in linktable.Rows)
            {
                linkBreakX = dr["BreakX"].ToString();
                linkBreakY = dr["BreakY"].ToString();
                startTaskId = dr["startTaskId"].ToString();//起端任务节点，由此来判断线的颜色。
                endTaskId = dr["EndTaskId"].ToString();//末端任务节点，由此来判断线的颜色。
                starttaskX = Convert.ToInt16((dr["starttaskX"] == null || dr["starttaskX"].ToString() == "") ? 0 : dr["starttaskX"]);
                starttaskY = Convert.ToInt16((dr["starttaskY"] == null || dr["starttaskY"].ToString() == "") ? 0 : dr["starttaskY"]);
                endtaskX = Convert.ToInt16((dr["endtaskX"] == null || dr["endtaskX"].ToString() == "") ? 0 : dr["endtaskX"]);
                endtaskY = Convert.ToInt16((dr["endtaskY"] == null || dr["endtaskY"].ToString() == "") ? 0 : dr["endtaskY"]);
                startLX = Convert.ToInt32((dr["startLx"] == null || dr["startLx"].ToString() == "") ? 0 : dr["startLx"]);
                startLY = Convert.ToInt32((dr["startLy"] == null || dr["startLy"].ToString() == "") ? 0 : dr["startLy"]);
                endLX = Convert.ToInt32((dr["endLx"] == null || dr["endLx"].ToString() == "") ? 0 : dr["endLx"]);
                endLY = Convert.ToInt32((dr["endLy"] == null || dr["endLy"].ToString() == "") ? 0 : dr["endLy"]);
                linkDes = dr["Description"].ToString();
                started = client.IsPassJudge(workflowId, workflowInsId, startTaskId, WorkFlowConst.Command_And);
                ended = client.IsPassJudge(workflowId, workflowInsId, endTaskId, WorkFlowConst.Command_And);
                fromStart = isFromStartTask(workflowId, workflowInsId, startTaskId, endTaskId);
                isPass = (started && ended && fromStart);
                if (isPass) linkColor = Color.Red; else linkColor = Color.Black;
                drawLinkBitMap(gc, linkBreakX, linkBreakY, starttaskX, starttaskY, endtaskX, endtaskY, startLX, startLY, endLX, endLY,linkColor, linkDes);
            }

        }
	}
}